<template>
  <div class="cart-page">
    <div class="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/home">{{ $t('menu.home') }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ $t('cart.title') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="actions">
        <el-button type="danger" :disabled="selectedRowIds.length === 0" @click="handleBatchRemove">{{ $t('cart.batchDelete') }}</el-button>
        <el-button type="primary" :disabled="selectedRowIds.length === 0" @click="handleBatchFavorite">{{ $t('cart.moveToFavorite') }}</el-button>
      </div>
    </div>

    <el-card class="card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">{{ $t('cart.cartList') }}</span>
          <el-button
            type="warning"
            text
            :disabled="selectedRowIds.length === 0"
            @click="confirmClearSelection"
          >{{ $t('cart.clearSelected') }}</el-button>
        </div>
      </template>
      <el-table
        ref="tableRef"
        :data="displayedItems"
        :row-key="row => row.id"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" reserve-selection />
        <el-table-column :label="$t('cart.product')" min-width="300">
          <template #default="{ row, $index }">
            <div class="product-cell">
              <img
                class="thumb thumb-clickable"
                :src="row.imageUrl"
                alt="thumb"
                loading="lazy"
                @error="onImgError"
                @click="openPreviewAt($index)"
              />
              <div class="meta">
                <div class="title">{{ row.title }}</div>
                <div class="sku">{{ row.sku || $t('cart.defaultSku') }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('cart.unitPrice')" width="130" align="right">
          <template #default="{ row }">
            ￥{{ formatPrice(row.price) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('cart.quantity')" width="170" align="center">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.quantity" 
              :min="1" 
              :max="999" 
              :default-value="1"
              class="cart-quantity-input"
              @change="onQuantityChange(row)" 
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('cart.subtotal')" width="150" align="right">
          <template #default="{ row }">
            <span class="subtotal">￥{{ formatPrice(row.price * row.quantity) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('cart.action')" width="180" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleRemove(row.id)">{{ $t('cart.delete') }}</el-button>
            <el-divider direction="vertical" />
            <el-button link type="info" @click="handleFavorite(row.id)">{{ $t('cart.favorite') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="pagination-card" shadow="never">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
      />
    </el-card>

    <el-card class="summary" shadow="never">
      <div class="summary-left">
        <el-checkbox v-model="isAllSelected" @change="toggleSelectAll">{{ $t('cart.selectAll') }}</el-checkbox>
        <span class="sep" />
        {{ $t('cart.selected') }} <b>{{ selectedRowIds.length }}</b> {{ $t('cart.items') }}
      </div>
      <div class="summary-right">
        <div class="price-line">
          {{ $t('cart.total') }}：<span class="total">{{ formatCNY(totalSelectedAmount) }}</span>
          <span v-if="totalDiscount > 0" class="discount">{{ $t('cart.discounted') }}￥{{ formatPrice(totalDiscount) }}</span>
        </div>
        <el-button type="primary" size="large" :disabled="selectedRowIds.length === 0" @click="handleCheckout">
          {{ $t('cart.checkout') }}
        </el-button>
      </div>
    </el-card>
    
    <!-- 图片预览：使用 Element Plus ImageViewer，全屏覆盖更适合图片预览 -->
    <teleport to="body">
      <el-image-viewer
        v-if="previewVisible"
        :url-list="currentPreviewList"
        :initial-index="previewIndex"
        :z-index="3000"
        @close="previewVisible = false"
      />
    </teleport>
  </div>
  
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElImageViewer, ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user';
import cartApi from '@/api/cart.js';

const { t } = useI18n();
const userStore = useUserStore();

// 购物车数据
const cartItems = ref([])
const loading = ref(false)
const totalItems = ref(0) // 后端分页：总记录数

const selectedRowIds = ref([]);
const tableRef = ref(null);
const isSyncingSelection = ref(false);

// 分页
const currentPage = ref(1);
const pageSize = ref(10); // 改为10条/页，与后端保持一致

// 加载购物车数据（后端分页）
const loadCartData = async () => {
  try {
    loading.value = true
    const response = await cartApi.getCartList(currentPage.value, pageSize.value)
    
    // axios拦截器已经处理了错误情况，这里直接使用成功的数据
    if (response && response.data && response.data.records) {
      // 转换后端数据格式为前端展示格式
      cartItems.value = response.data.records.map(item => ({
        id: item.id.toString(),
        title: item.productName,
        sku: item.sku || t('cart.defaultSku'),
        price: item.price, // ✅ 修复：后端已经是分为单位，不要再乘以100！
        quantity: item.quantity || 1, // 确保数量至少为1
        imageUrl: item.imageUrl || 'https://images.unsplash.com/photo-1518779578993-ec3579fee39f?auto=format&fit=crop&w=128&q=80'
      }))
      totalItems.value = response.data.total || 0 // 设置总记录数
    } else {
      cartItems.value = []
      totalItems.value = 0
    }
  } catch (error) {
    console.error('加载购物车数据失败:', error)
    ElMessage.error(t('cart.loadFailed'))
  } finally {
    loading.value = false
  }
}

// 页面挂载时加载数据
onMounted(() => {
  loadCartData()
})

// 后端分页：直接显示当前页数据
const displayedItems = computed(() => cartItems.value);

const cnyFormatter = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 });
const formatPrice = (cents) => (cents / 100).toFixed(2);
const formatCNY = (cents) => cnyFormatter.format(cents / 100);

const handleSelectionChange = (selection) => {
  if (isSyncingSelection.value) return;
  const set = new Set(selectedRowIds.value);
  for (const item of displayedItems.value) set.delete(item.id);
  for (const item of selection) set.add(item.id);
  selectedRowIds.value = Array.from(set);
};

const isAllSelected = computed({
  get() {
    // ✅ 修复：后端分页时，全选只选中当前页
    return displayedItems.value.length > 0 && 
           displayedItems.value.every(item => selectedRowIds.value.includes(item.id));
  },
  set(val) {
    if (val) {
      // 全选当前页
      const currentPageIds = displayedItems.value.map(i => i.id);
      const set = new Set(selectedRowIds.value);
      currentPageIds.forEach(id => set.add(id));
      selectedRowIds.value = Array.from(set);
    } else {
      // 取消全选当前页
      const currentPageIds = new Set(displayedItems.value.map(i => i.id));
      selectedRowIds.value = selectedRowIds.value.filter(id => !currentPageIds.has(id));
    }
  }
});

const toggleSelectAll = (val) => {
  isAllSelected.value = val;
  nextTick(syncPageSelection);
};

let qtyChangeTimer = null;
const onQuantityChange = async (row) => {
  if (row.quantity < 1) row.quantity = 1;
  if (qtyChangeTimer) clearTimeout(qtyChangeTimer);
  qtyChangeTimer = setTimeout(async () => {
    try {
      // ✅ 修复：移除username参数，后端从Session获取当前用户
      const response = await cartApi.updateCartQuantity({
        cartId: parseInt(row.id),
        quantity: row.quantity
      })
      if (!response.success) {
        ElMessage.error(response.msg || t('cart.updateQuantityFailed'))
        await loadCartData() // 重新加载数据恢复
      }
    } catch (error) {
      console.error('更新购物车数量失败:', error)
      ElMessage.error(t('cart.updateFailed'))
      await loadCartData() // 重新加载数据恢复
    }
  }, 250);
};

const handleRemove = async (id) => {
  ElMessageBox.confirm(t('cart.confirmDelete'), t('cart.hint'), { type: 'warning' })
    .then(async () => {
      try {
        const response = await cartApi.removeFromCart(parseInt(id))
        if (response.success) {
          cartItems.value = cartItems.value.filter(i => i.id !== id)
          selectedRowIds.value = selectedRowIds.value.filter(i => i !== id)
          ElMessage.success(t('cart.deleted'))
        } else {
          ElMessage.error(response.msg || t('cart.deleteFailed'))
        }
      } catch (error) {
        console.error('删除购物车商品失败:', error)
        ElMessage.error(t('cart.deleteFailedRetry'))
      }
    })
    .catch(() => {})
}

const handleBatchRemove = () => {
  if (selectedRowIds.value.length === 0) return
  ElMessageBox.confirm(t('cart.confirmBatchDelete', { count: selectedRowIds.value.length }), t('cart.hint'), { type: 'warning' })
    .then(async () => {
      try {
        const cartIds = selectedRowIds.value.map(id => parseInt(id))
        // ✅ 修复：移除username参数，后端从Session获取当前用户
        const response = await cartApi.batchRemoveFromCart(cartIds)
        if (response.success) {
          // ✅ 修复：删除后重新加载数据（后端分页）
          await loadCartData()
          selectedRowIds.value = []
          ElMessage.success(t('cart.batchDeleteSuccess'))
        } else {
          ElMessage.error(response.msg || t('cart.batchDeleteFailed'))
        }
      } catch (error) {
        console.error('批量删除购物车商品失败:', error)
        ElMessage.error(t('cart.batchDeleteFailedRetry'))
      }
    })
    .catch(() => {})
}

const handleFavorite = (id) => {
  ElMessage.success(t('cart.movedToFavorite'))
}

const handleBatchFavorite = () => {
  if (selectedRowIds.value.length === 0) return
  ElMessageBox.confirm(t('cart.confirmMoveToFavorite', { count: selectedRowIds.value.length }), t('cart.moveToFavorite'), { type: 'info' })
    .then(() => {
      ElMessage.success(t('cart.batchMovedToFavorite'))
    })
    .catch(() => {})
}

const totalSelectedAmount = computed(() => {
  const set = new Set(selectedRowIds.value)
  return cartItems.value
    .filter(i => set.has(i.id))
    .reduce((sum, i) => sum + i.price * i.quantity, 0)
})

const totalDiscount = computed(() => {
  // 示例：满 200 减 10（仅对选中项模拟）
  const amount = totalSelectedAmount.value
  if (amount >= 20000) return 1000
  return 0
})

const handleCheckout = async () => {
  if (selectedRowIds.value.length === 0) return
  
  try {
    const cartIds = selectedRowIds.value.map(id => parseInt(id))
    // ✅ 修复：移除username参数，后端从Session获取当前用户
    const response = await cartApi.checkoutCart({
      cartIds: cartIds
    })
    if (response.success) {
      ElMessage.success(t('cart.checkoutSuccess', { orderNo: response.data?.[0]?.orderNo || '已生成' }))
      // 重新加载购物车数据
      await loadCartData()
      selectedRowIds.value = []
    } else {
      ElMessage.error(response.msg || t('cart.checkoutFailed'))
    }
  } catch (error) {
    console.error('购物车结算失败:', error)
    ElMessage.error(t('cart.checkoutFailedRetry'))
  }
}

const fallbackImageUrl = 'https://images.unsplash.com/photo-1518779578993-ec3579fee39f?auto=format&fit=crop&w=128&q=80'
const onImgError = (event) => {
  if (event && event.target) {
    event.target.src = fallbackImageUrl
    event.target.onerror = null
  }
}

// 清空已选（仅取消勾选，不删除任何条目）
const confirmClearSelection = () => {
  if (selectedRowIds.value.length === 0) return
  ElMessageBox.confirm(
    t('cart.confirmClearSelection', { count: selectedRowIds.value.length }),
    t('cart.clearSelected'),
    { type: 'warning' }
  )
    .then(() => {
      selectedRowIds.value = []
      nextTick(syncPageSelection)
      ElMessage.success(t('cart.selectionCleared'))
    })
    .catch(() => {})
}

// 受控图片预览
const previewVisible = ref(false)
const previewIndex = ref(0)
const currentPreviewList = computed(() => displayedItems.value.map(i => i.imageUrl || fallbackImageUrl))
const openPreviewAt = (idx) => {
  previewIndex.value = idx
  previewVisible.value = true
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  loadCartData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadCartData()
}

const syncPageSelection = () => {
  if (!tableRef.value) return
  isSyncingSelection.value = true
  tableRef.value.clearSelection()
  const set = new Set(selectedRowIds.value)
  for (const row of displayedItems.value) {
    if (set.has(row.id)) tableRef.value.toggleRowSelection(row, true)
  }
  nextTick(() => {
    isSyncingSelection.value = false
  })
}

watch([displayedItems], () => nextTick(syncPageSelection))
watch(selectedRowIds, () => nextTick(syncPageSelection))
</script>

<style scoped src="@/styles/Cart.scss"></style>


